package com.xing.config.ds.multi;

import com.baomidou.mybatisplus.entity.GlobalConfiguration;
import com.baomidou.mybatisplus.enums.IdType;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Properties;

/**
 * Created by Bradish7Y on 2017/8/24.
 */
@Configuration
@MapperScan(value = "com.xing.dao.one", sqlSessionFactoryRef = "sqlSessionFactoryOne")
public class SqlSessionFactoryOneConfig {

    @Resource(name = "datasource_one")
    private DataSource dataSourceOne;

    /**
     * mybatis-plus
     */
    @Bean
    public GlobalConfiguration globalConfigurationOne() {
        GlobalConfiguration g = new GlobalConfiguration();
        g.setIdType(IdType.AUTO.getKey());

        return g;
    }

    @Bean
    public Properties propertiesOne() {
        Properties prop = new Properties();
        prop.setProperty("cacheModelsEnabled", "true");
        prop.setProperty("enhancementEnabled", "true");
        prop.setProperty("lazyLoadingEnabled", "false");
        prop.setProperty("errorTracingEnabled", "true");
        prop.setProperty("maxRequests", "32");
        prop.setProperty("maxSessions", "10");
        prop.setProperty("maxTransactions", "5");
        prop.setProperty("useStatementNamespaces", "true");

        return prop;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactoryOne() throws Exception {
        MybatisSqlSessionFactoryBean sessionFactory = new MybatisSqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSourceOne);
        //实体类所在的包
        sessionFactory.setTypeAliasesPackage("com.xing.entity");

        sessionFactory.setConfigurationProperties(propertiesOne());

        sessionFactory.setGlobalConfig(globalConfigurationOne());

        //mapper*.xml的位置，特殊需求还是要配置在xml里
//        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().
//                getResources("classpath:mapper/read/*.xml"));

        //分页
        PaginationInterceptor pageInterceptor = new PaginationInterceptor();
        Properties pageProp = new Properties();
        pageProp.setProperty("dialectType", "mysql");
        pageInterceptor.setProperties(pageProp);

        sessionFactory.setPlugins(new Interceptor[]{pageInterceptor});//分页

        return sessionFactory.getObject();
    }
}
